class LoginController < ApplicationController
  
  layout :determine_layout

  def add_user
    @user = User.new(params[:user])
    if request.post? and @user.save
      flash.now[:notice] = "User #{@user.name} created"
      session[:user_id] = @user.id
      session[:original_uri] = request.request_uri
      redirect_to(:action => "additional_info")
    end
  end
  
  def additional_info
    @user = User.find_by_id(session[:user_id])
    if @user and request.get?
      if @user.person
        @person = @user.person
      else
        @person = Person.new
      end
    elsif @user and request.post?
      uri = session[:original_uri]
      if @user.person
        @person = @user.person
      else
        @person = Person.new()
      end
      @person.update_attributes(params[:person])
      if @person.email.blank? and !@user.email.blank?
        @person.email = @user.email
      end
      if @person.save
        @user.person = @person
        if @user.save
          flash[:notice] = 'Information was successfully added'
          redirect_to(uri || {:controller => 'fabrics', :action => "index" })
        else
          flash[:notice] = 'There was a problem saving the user'
          redirect_to :action => 'additional_info'
        end
      else
        flash[:notice] = 'There was a problem saving the additional info'
        redirect_to :action => 'additional_info'
      end 
    elsif !@user
      authorize
    end
  end

  def login
    session[:user_id] = nil
    if request.post?
      user = User.authenticate(params[:name], params[:password])
      if user
        session[:user_id] = user.id
        uri = session[:original_uri]
        session[:original_uri] = nil
        if uri.nil?
          uri = "fabrics"
        end
        redirect_to(uri || {:action => "index"})
      else
        flash[:notice] = "Invalid user/password combination"
      end
    end
  end

  def logout
    session[:user_id] = nil
    flash[:notice] = "Logged Out"
    redirect_to(:action => "login")
  end

  def index
  end

  def delete_user
  end

  def list_users
    
  end
end
